import Vue from "vue";
import VueRouter from "vue-router";
import { Message } from "element-ui";
import Home from "../views/Home";
import Login from "../views/Login";
import Register from "../views/Register";
import Search from "../views/Search";
import Detail from "../views/Detail";
import AddCartSuccess from "../views/AddCartSuccess";
import ShopCart from "@/views/ShopCart";
import Center from "@/views/Center";
import Trade from "@/views/Trade";
import Pay from "@/views/Pay";
import PaySuccess from "@/views/PaySuccess";
import store from "@/store";

Vue.use(VueRouter);

const routers = new VueRouter({
  mode: "history",
  routes: [
    {
      path: "/",
      redirect: "/home",
    },
    {
      path: "/home",
      component: Home, //读取不到isshowFooter值为undefined !undefined为true
    },
    {
      path: "/login",
      component: Login,
      meta: {
        isshowFooter: true,
      },
    },

    {
      path: "/register",
      component: Register,
      meta: {
        isshowFooter: true, //读取到值为true 取反  v-if=:'false' 所有不显示
      },
    },
    {
      name: "Search",
      path: "/search",
      component: Search,
    },
    {
      path: "/detail/:id",
      name: "Detail",
      component: Detail,
    },
    {
      path: "/addcart_success",
      name: "AddCartSuccess",
      component: AddCartSuccess,
    },
    {
      path: "/shopCart",
      component: ShopCart,
    },
    {
      path: "/center",
      name: "Center",
      component: Center,
    },
    {
      path: "/pay",
      name: "Pay",
      component: Pay,
    },
    {
      path: "/trade",
      name: "Trade",
      component: Trade,
    },
    {
      path: "/paysuccess",
      name: "PaySuccess",
      component: PaySuccess,
    },
  ],
  // 每次路由跳转会触发的函数
  scrollBehavior() {
    return {
      x: 0,
      y: 0,
    };
  },
});

// 需要
const pathArray = ["/center", "/pay", "/trade", "/addcart_success","/shopcart"];

routers.beforeEach((to, from, next) => {
  const token = store.state.user.token;
  // 有登录
  if (token) {
    if (to.path === "/login") {
      next("/");
    } else {
      next();
    }
  } else {
    // 没登录
    if (pathArray.includes(to.path)) {
      Message.error("请先登录，在访问");
      next(`/login?redirct=${to.path}`);
    } else {
      next();
    }
  }
});

export default routers;
